import axios from 'axios';
import Vue from 'vue';
import Cookies from 'js-cookie';
import router from '../router';

// create an axios instance
const service = axios.create({
	baseURL: '/api', // api 的 base_url
	timeout: 5000 // request timeout
});

service.interceptors.request.use(
	config => {
		if (config.method === 'get') {
			// 解决ie浏览器缓存问题
			if (config.params) {
				config.params['t'] = new Date().getTime();
			} else {
				config['params'] = { t: new Date().getTime() };
			}
		}
		// 修改发送参数
        config.headers['Content-Type'] = 'application/json;charset=UTF-8';
		config.headers['Accept'] = 'application/json';
		config.headers['token'] = Cookies.get('token');
		config.data = JSON.stringify(config.data);
		return config;
	},
	error => {
		// Do something with request error
		console.log(error); // for debug
		Promise.reject(error);
	}
);

// 请求返回
service.interceptors.response.use(
	response => {
		const res = response.data;
		// 普通api请求返回
		if (res.code === 0) {
			return res;
		} else if (res.code === 401) {
			router.push({ path: '/login' });
			Vue.prototype.$message.error('登录失效，请重新登录');
		} else {
			throw new Error(res.msg ? res.msg : '未知错误');
			Vue.prototype.$message.error(res.msg);
		}
	},
	error => {
		console.log('err' + error); // for debug
		return Promise.reject(error);
	}
);

export default service;
